package com.dongdongshop.front.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //创建ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(){
        ShiroFilterFactoryBean filterFactoryBean=new ShiroFilterFactoryBean();
        //设置安全管理器
        filterFactoryBean.setSecurityManager(getDefaultWebSecurityManager());
        //设置shiro内置过滤器
        Map<String,String> filemap=new LinkedHashMap<>();

        //放过静态资源
        filemap.put("/**","anon");

        //其余的都要认证
        //filemap.put("/**","authc");

        //实现退出
        filemap.put("/auth/logout","logout");

        //自定义登录页面
        /*filterFactoryBean.setLoginUrl("/login/toLogin");
        filterFactoryBean.setFilterChainDefinitionMap(filemap);*/
        //登陆后没有权限，返回到登陆页面
        //filterFactoryBean.setUnauthorizedUrl("/loginController/tologin");
        return filterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        //关联realm
        securityManager.setRealm(getRealm());
        return securityManager;
    }

    @Bean
    public Realm getRealm(){
        Realm realm=new Realm();
        realm.setCredentialsMatcher(getHashedCredentialsMatcher());
        return realm;
    }

    @Bean
    public HashedCredentialsMatcher getHashedCredentialsMatcher(){
        HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();
        //指定加密方式
        credentialsMatcher.setHashAlgorithmName("MD5");
        //加密次数
        credentialsMatcher.setHashIterations(10);
        //此处的加密，true加密用的是hex编码，false加密用的是base64编码
        credentialsMatcher.setStoredCredentialsHexEncoded(true);
        return credentialsMatcher;
    }


}
